package main

import (
	"encoding/json"
	"fmt"
	"log"
	"time"

	sls "github.com/aliyun/aliyun-log-go-sdk"
)

func main() {
	Endpoint := "cn-hongkong.log.aliyuncs.com"
	AccessKeyId := "LTAI5tGjJnh66c1txANiRBQN"
	AccessKeySecret := "IZa8HrpmQh7xzd0TIEFQe8YpRX8zOh"
	SecurityToken := ""
	ProjectName := "wxhk-backend"
	LogStoreName := "gw-kong-log"
	topic := ""
	var offset int64 = 0
	var pageSize int64 = 100
	endAt := time.Now().Unix()
	startAt := endAt - 3600*24*30

	client := sls.CreateNormalInterface(Endpoint, AccessKeyId, AccessKeySecret, SecurityToken)

	// 创建项目
	// Description := "test"
	// project, err := client.CreateProject(ProjectName, Description)
	// if err != nil {
	// 	if e, ok := err.(*sls.Error); ok && e.Code == "ProjectAlreadyExist" {
	// 		log.Printf("Project : %s already created or has an global name conflict in Aliyun scope", ProjectName)
	// 	} else {
	// 		log.Fatalf("Create project : %s failed %v", ProjectName, err)
	// 	}
	// }

	// 创建存储
	// err := client.CreateLogStore(ProjectName, LogStoreName, 3, 2, true, 6)
	// if err != nil {
	// 	if e, ok := err.(*sls.Error); ok && e.Code == "LogStoreAlreadyExist" {
	// 		log.Printf("Logstore : %s already created", LogStoreName)
	// 	} else {
	// 		log.Fatalf("Create LogStore : %s failed %v", LogStoreName, err)
	// 	}
	// }

	// 创建索引
	// index := sls.Index{
	// 	Keys: map[string]sls.IndexKey{
	// 		"col_0": {
	// 			Token:         []string{" "},
	// 			CaseSensitive: false,
	// 			Type:          "long",
	// 		},
	// 		"col_1": {
	// 			Token:         []string{",", ":", " "},
	// 			CaseSensitive: false,
	// 			Type:          "text",
	// 		},
	// 	},
	// 	Line: &sls.IndexLine{
	// 		Token:         []string{",", ":", " "},
	// 		CaseSensitive: false,
	// 		IncludeKeys:   []string{},
	// 		ExcludeKeys:   []string{},
	// 	},
	// }
	// err := client.CreateIndex(ProjectName, LogStoreName, index)
	// if err != nil {
	// 	if e, ok := err.(*sls.Error); ok && e.Code == "IndexAlreadyExist" {
	// 		log.Printf("Index : already created")
	// 	} else {
	// 		log.Fatalf("Create Index failed %v", err)
	// 	}
	// }

	// 写入日志
	// for loggroupIdx := 0; loggroupIdx < 10; loggroupIdx++ {
	// 	logs := []*sls.Log{}
	// 	for logIdx := 0; logIdx < 100; logIdx++ {
	// 		content := []*sls.LogContent{}
	// 		for colIdx := 0; colIdx < 10; colIdx++ {
	// 			if colIdx == 0 {
	// 				content = append(content, &sls.LogContent{
	// 					Key5:   proto.String(fmt.Sprintf("col_%d", colIdx)),
	// 					Value: proto.String(fmt.Sprintf("%d", rand.Intn(10000000))),
	// 				})
	// 			} else {
	// 				content = append(content, &sls.LogContent{
	// 					Key5:   proto.String(fmt.Sprintf("col_%d", colIdx)),
	// 					Value: proto.String(fmt.Sprintf("loggroup idx: %d, log idx: %d, col idx: %d, value: %d", loggroupIdx, logIdx, colIdx, rand.Intn(10000000))),
	// 				})
	// 			}
	// 		}
	// 		log := &sls.Log{
	// 			Time:     proto.Uint32(uint32(time.Now().Unix())),
	// 			Contents: content,
	// 		}
	// 		logs = append(logs, log)
	// 	}
	// 	loggroup := &sls.LogGroup{
	// 		Topic:  proto.String("test"),
	// 		Source: proto.String("203.0.113.10"),
	// 		Logs:   logs,
	// 	}
	//
	// 	err := client.PutLogs(ProjectName, LogStoreName, loggroup)
	// 	if err != nil {
	// 		log.Fatalf("PutLogs failed %v", err)
	// 	}
	// }

	items := []string{
		"396204715",
		"109538641",
		"872854906",
		"396204715",
		"181953670",
		"181953670",
	}
	for _, item := range items {
		response, err := client.GetLogs(ProjectName, LogStoreName, topic, startAt, endAt, fmt.Sprintf("%s and /api/mirror/code", item), pageSize, offset, true)
		if err != nil {
			log.Fatalf("GetLogs failed %v", err)
		}

		if response.Count > 0 {
			var request Request
			err = json.Unmarshal([]byte(response.Logs[0]["raw"]), &request)
			if err != nil {
				panic(err)
			}
			fmt.Println(request.ClientIp)
		} else {
			fmt.Println("")
		}
	}
}

type Request struct {
	StartedAt int64  `json:"started_at"`
	ClientIp  string `json:"client_ip"`
	// Request string
	Status uint
	// Response string
	Hostname    string
	UpstreamUri string `json:"upstream_uri"`
	// Service string
	// Route string
	// Tries string
	// Latencies string
}

// type Student struct {
// 	Name string
// 	Age int
// 	Skill string
// }

// stu := Student{"tom", 12, "football"}
// data, err := json.Marshal(&stu)
// if err != nil {
// 	panic(err)
// }
// fmt.Println(string(data))

// str := `{"Name":"tom","Age":12,"Skill":"football"}`
// var stu2 Student
// err := json.Unmarshal([]byte(str), &stu2)
// if err != nil {
// 	panic(err)
// }
// fmt.Printf(stu2)
